package com.ltmonitor.web.controller.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.ltmonitor.web.util.OnlineUser;

public class HandShakeInterceptor extends HttpSessionHandshakeInterceptor {
	protected Logger logger = Logger.getLogger(getClass());

	@Override
	public boolean beforeHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		//System.out.println("Before Handshake");
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			HttpSession session = servletRequest.getServletRequest()
					.getSession(false);
			if (session != null) {
				// 使用userName区分WebSocketHandler，以便定向发送消息
				OnlineUser user = (OnlineUser) session
						.getAttribute("currUserInfo");
				if (user != null) {
					String userName = user.getName();
					// logger.info(userName+" login");
					attributes.put("userName", userName);
					attributes.put("onlineUser", user);
				}
			} else {
				logger.debug("httpsession is null");
			}
		}
		return true;
	}

	@Override
	public void afterHandshake(ServerHttpRequest request,
			ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception ex) {
		//System.out.println("After Handshake");
		super.afterHandshake(request, response, wsHandler, ex);
	}
}